using UnityEngine;
using System.Collections;

public class Connection : MonoBehaviour
{
	public Transform player1;
	public Transform player2;
    public string remoteIP = "127.0.0.1";
	public string yourIP = "";
    public string yourPort = "";
    public int remotePort = 8001;
    public int listenPort = 8001;
    public bool useNAT = false;
	public bool easyMode = true;
	public bool hardMode = false;
	public static bool playersConnected = false;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
	
	void  OnConnectedToServer ()
    {
        foreach (GameObject go in FindObjectsOfType(typeof(GameObject)))
            go.SendMessage("OnNetworkLoadedLevel", SendMessageOptions.DontRequireReceiver); 
    }
	
    void  OnNetworkLoadedLevel()
    {
		Network.Instantiate(player2,player2.transform.position,Quaternion.identity,0);
		playersConnected = true;
    }

    void OnGUI()
    {
        if (Network.peerType == NetworkPeerType.Disconnected)
        {
            if (GUI.Button (new Rect(10,10,100,30),"Connect"))
            {
                Network.Connect(remoteIP, remotePort);
            }
			
            if (GUI.Button (new Rect(10,50,100,30),"Start Server"))
            {
                Network.InitializeServer(32, listenPort, useNAT);
				Network.Instantiate(player1,player1.transform.position,Quaternion.identity,0);
            }
			
			if(GUI.Toggle(new Rect(120,40,100,20), easyMode,"Easy Mode"))
			{
				easyMode = true;
				hardMode = false;
			}
			
			if(GUI.Toggle(new Rect(120,60,100,20), hardMode,"Hard Mode"))
			{
				easyMode = false;
				hardMode = true;
			}

            remoteIP = GUI.TextField(new Rect(120,10,100,20),remoteIP);
            remotePort = int.Parse(GUI.TextField(new Rect(230,10,40,20),remotePort.ToString()));

        }
        else
        {
            GUI.Label(new Rect(140,20,250,40),
                "IP Adress: " + Network.player.ipAddress + ":" + Network.player.port.ToString());

            if (GUI.Button (new Rect(10,10,100,50),"Disconnect"))
            {
                Network.Disconnect(200);
				Application.LoadLevel(Application.loadedLevel);
            }
        }
    }
	
	void OnPlayerDisconnected(NetworkPlayer player)
    {
        Network.RemoveRPCs(player, 0);
        Network.DestroyPlayerObjects(player);
		Application.LoadLevel(Application.loadedLevel);
    }
}